package itheima.propertor;


import itheima.domain.Student;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Scanner;

public class StudentOperator {
    Scanner sc=new Scanner(System.in);
    private static ArrayList<Student>list = new ArrayList<>();
    /*增加学生*/
    public void addstudent() {
        System.out.println("请输入要添加的学号");
        String sid = sc.nextLine();
        int index = getIndex(sid);
        if (index<0){
            System.out.println("请输入姓名");
            String name = sc.nextLine();
            System.out.println("请输入年龄");
            String ageStr = sc.nextLine();
            Integer age = Integer.parseInt(ageStr);
            System.out.println("请输入生日");
            String birthdayStr = sc.nextLine();
            LocalDate birthday = LocalDate.parse(birthdayStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            Student stu = new Student(sid, name, age, birthday);
            list.add(stu);
            System.out.println("添加成功");
        }else {
            System.out.println("学号不存在");
        }
        }

    /*删除学生*/
    public void deletestudent() {
        System.out.println("请输入要删除的学生");
        String sid = sc.nextLine();
        int index = getIndex(sid);
        if (index>=0){
            list.remove(index);
            System.out.println("删除成功");
        }else{
            System.out.println("删除的学号不存在");
        }
    }
   /* 修改学生*/
    public void updatestudent() {
        while (true){

        System.out.println("请输入要修改的学号");
        String sid = sc.nextLine();
        /* 根据学号找索引*/
        int index=getIndex(sid);
        if (index>0){
            System.out.println("请输入姓名");
            String name = sc.nextLine();
            System.out.println("请输入年龄");
            String ageStr = sc.nextLine();
            Integer age = Integer.parseInt(ageStr);
            System.out.println("请输入生日");
            String birthdayStr = sc.nextLine();
            LocalDate birthday = LocalDate.parse(birthdayStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            Student stu = new Student(sid, name, age, birthday);
            list.set(index,stu);
            System.out.println("修改成功");
        }else {
            System.out.println("学号不存在");
        }
        }
    }

    private int getIndex(String sid) {
        if (list==null ||list.size()==0 ){

        return -1;
        }
        for (int i = 0; i < list.size(); i++) {
            Student student = list.get(i);
            if (student.getSid().equals(sid)){
                return i;
            }
        }
        return -1;
    }

    /* 查询学生*/
    public void findallstudent() {
        if (list == null || list.size()==0){
            System.out.println("没有数据请先添加");
            return;
        }
        System.out.println("学生学号 姓名 年龄 生日");
        list.forEach(student -> System.out.println(student.getSid()+"\t"+student.getName()+"\t"+student.getAge()+"\t"+student.getBirthday()));
    }
}
